package cc.minos.servers.openfire.managers
{
	import cc.minos.servers.openfire.events.RoomsEvent;
	import org.igniterealtime.xiff.conference.Room;
	import org.igniterealtime.xiff.core.Browser;
	import org.igniterealtime.xiff.core.EscapedJID;
	import org.igniterealtime.xiff.core.UnescapedJID;
	import org.igniterealtime.xiff.core.XMPPConnection;
	import org.igniterealtime.xiff.data.disco.ItemDiscoExtension;
	import org.igniterealtime.xiff.data.IQ;
	import org.igniterealtime.xiff.data.muc.MUCExtension;
	import org.igniterealtime.xiff.events.RoomEvent;
	
	/**
	 * ...
	 * @author Minos
	 */
	public class MUCManager extends BasicManager
	{
		private var rooms:Object = {};
		private var brower:Browser;
		
		public function MUCManager( con:XMPPConnection )
		{
			super( con );
			brower = new Browser( con );
			//
		}
		
		public function getRoom( roomJID:UnescapedJID , name:String = null ):Room
		{
			var room:Room = rooms[ roomJID.bareJID ];
			if ( !room )
			{
				room = new Room( con );
				room.roomJID = roomJID;
				room.addEventListener( RoomEvent.ROOM_LEAVE , function( evt:RoomEvent ):void
					{
						rooms[ roomJID.bareJID ] = null;
					} );
				if ( name )
					room.roomName = name;
				rooms[ roomJID.bareJID ] = room;
				
				//set room's nickname
				room.nickname = OpenFireManager.config.nickname;
				
			}
			return room;
		}
		
		/**
		 * 获取服务内容
		 * 用于获取房间列表
		 * @param	jid		:	房间列表在 (service+domain) 服务中 默认conference
		 */
		public function getConferenceItems( jid:UnescapedJID ):void
		{
			brower.getServiceItems( jid.escaped , serviceChatsCall );
		}
		
		private function serviceChatsCall( iq:IQ ):void
		{
			var chats:Array = [];
			var extensions:Array = iq.getAllExtensions();
			for ( var s:int = 0 ; s < extensions.length ; ++s )
			{
				var disco:ItemDiscoExtension = extensions[ s ];
				var items:Array = disco.items;
				
				for ( var i:uint = 0 ; i < items.length ; ++i )
				{
					var obj:Object = {};
					
					trace( items[ i ].jid );
					
					obj.jid = new UnescapedJID( items[ i ].jid.toString() );
					obj.displayName = items[ i ].name;
					
					chats.push( obj );
				}
			}
			var evt:RoomsEvent = new RoomsEvent( RoomsEvent.ROOMS_LIST_UPDATED );
			evt.rooms = chats;
			broadcastEvent( evt );
		}
	
	}

}